﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;

/// <summary>
/// Mike
/// </summary>
public class Part
{
    List<Question> questions;
    int id;
    string title;
    string description;
    int max_mark;
    bool has_yesno;
    string yesno_description;
    int no;
    IDictionary<int, string> mark_description;

    public List<Question> Questions { get { return questions; } }
    public int ID { get { return id; } }
    public string Title { get { return title; } }
    public string Description { get { return description; } }
    public int MaxMark { get { return max_mark; } }
    public bool HasYesno { get { return has_yesno; } }
    public string YesnoDescription { get { return yesno_description; } }
    public int No { get { return no; } }
    public IDictionary<int, string> MarkDescription { get { return mark_description; } }

    public static IEnumerable<Part> Load(IDbConnection connection)
    {
        string sql_script =
@"SELECT * FROM [Parts] ORDER BY [Parts].no";
        IDbCommand cmd = connection.CreateCommand();
        cmd.CommandText = sql_script;
        IDataReader dr = cmd.ExecuteReader();
        List<Part> lst = new List<Part>();
        while (dr.Read())
        {
            Part part = new Part();

            part.id = Convert.ToInt32(dr["id"].ToString());
            part.no = part.id = Convert.ToInt32(dr["no"].ToString());
            part.title = dr["title"].ToString();
            part.description = dr["description"].ToString();
            part.max_mark = Convert.ToInt32(dr["max_mark"].ToString());
            part.yesno_description = dr["yesno_description"].ToString();
            part.has_yesno = !string.IsNullOrEmpty(part.yesno_description);

            lst.Add(part);
        }
        dr.Close();

        foreach (Part part in lst)
        {
            part.questions = Question.Load(part, connection);

        }
        foreach (Part part in lst)
        {
            part.mark_description = loadMarkDes(part.id, connection);
        }
        return lst;
    }

    static IDictionary<int, string> loadMarkDes(int part_id, IDbConnection connection)
    {
        string sql_script =
@"SELECT * FROM [MarkDetails] WHERE [MarkDetails].part_id = " + part_id;

        IDbCommand cmd = connection.CreateCommand();
        cmd.CommandText = sql_script;
        IDataReader dr = cmd.ExecuteReader();
        Dictionary<int, string> dic = new Dictionary<int, string>();
        while (dr.Read())
        {
            int mark = Convert.ToInt32(dr["mark"].ToString());
            string des = dr["description"].ToString();
            dic[mark] = des;
        }
        dr.Close();
        return dic;
    }
}